package main

import (
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"time"
)

const dsnDev string = "host=localhost user=postgres password='' dbname=hello-go-db port=5432 sslmode=disable TimeZone=Asia/Shanghai"
const dsnProd string = "host=db user=postgres password='abc123' dbname=hello port=5432 sslmode=disable TimeZone=Asia/Shanghai"

//const env = "development"

const env = "production"

type User struct {
	Id        int       `json:"id"`
	Username  string    `json:"username" gorm:"unique"`
	Password  string    `json:"password"`
	Name      string    `json:"name" gorm:"unique"`
	Age       int       `json:"age"`
	CreatedAt time.Time `gorm:"type:timestamptz" json:"createdAt"`
	UpdatedAt time.Time `gorm:"type:timestamptz" json:"updatedAt"`
}

func main() {
	var dsn string
	if env == "development" {
		dsn = dsnDev
	} else {
		dsn = dsnProd
	}
	fmt.Println("db:", "db")

	r := gin.Default()
	config := cors.DefaultConfig()
	config.AllowOrigins = []string{"http://localhost:4200"}

	r.Use(cors.New(config))

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println(err.Error())
	}
	db.AutoMigrate(
		&User{},
	)
	seed(db)
	if env == "development" {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	type IndexModel struct {
		Id int `uri:"id"`
	}
	r.GET("/:id", func(c *gin.Context) {
		var query IndexModel
		var err = c.ShouldBindUri(&query)
		if err != nil {
			fmt.Println(err.Error())
		}
		fmt.Println(query)

		var user User
		db.Find(&user, "id = ?", query.Id)
		c.JSON(200, gin.H{"data": user})
	})
	r.GET("/", func(c *gin.Context) {
		var user []User
		db.Find(&user)
		c.JSON(200, gin.H{"data": user})
	})
	r.Run() // 127.0.0.1:8000
}
func seed(db *gorm.DB) {
	var tmp []User
	db.Raw("select * from users").Scan(&tmp)
	if len(tmp) == 5 {
		fmt.Println("已经初始化过数据。")
		return
	}
	var users []User = []User{
		User{Username: "zhangsan", Password: "000000", Name: "张三", Age: 12},
		User{Username: "lisi", Password: "11111", Name: "李四", Age: 12},
		User{Username: "wangwu", Password: "222222", Name: "王五", Age: 12},
		User{Username: "zhaoliu", Password: "333333", Name: "赵六", Age: 12},
		User{Username: "huluwa", Password: "444444", Name: "葫芦娃", Age: 7},
	}
	db.Save(&users)
}
